import React, {useEffect, useState} from 'react';
import { Cascader } from 'antd';

import areas from "@/assets/china-division/dist/areas.json";
import cities from "@/assets/china-division/dist/cities.json";
import provinces from "@/assets/china-division/dist/provinces.json";

const RegionSelect = (props) => {

  const {setAddressStr} = props
  const [values, setValues] = useState(undefined)

  // 定义接口
  interface Area {
    code: string;
    name: string;
    cityCode?: string;
  }

  interface City {
    code: string;
    name: string;
    provinceCode: string;
    children?: AreaOption[];
  }

  interface Province {
    code: string;
    name: string;
    children?: CityOption[];
  }

  interface AreaOption {
    label: string;
    value: string;
  }

  interface CityOption extends AreaOption {
    children?: AreaOption[];
  }

// 将原始数据转换为带有 children 属性的类型
  const typedCities: City[] = cities.map((city) => ({...city, children: []}));
  const typedProvinces: Province[] = provinces.map((province) => ({
    ...province,
    children: []
  }));
  const typedAreas: Area[] = areas.map((area) => ({...area}));

  typedAreas.forEach((area) => {
    const matchCity = typedCities.find((city) => city.code === area.cityCode);
    if (matchCity) {
      matchCity.children!.push({
        label: area.name,
        value: area.name
      });
    }
  });

  typedCities.forEach((city) => {
    const matchProvince = typedProvinces.find(
      (province) => province.code === city.provinceCode
    );
    if (matchProvince) {
      matchProvince.children!.push({
        label: city.name,
        value: city.name,
        children: city.children
      });
    }
  });

  const options = typedProvinces.map((province) => ({
    label: province.name,
    value: province.name,
    children: province.children
  }));

  const onChange = (value: string[]) => {
    if(value !== undefined) {
      setAddressStr(JSON.stringify(value))
    }
  };


  return (
    <div>
      <Cascader value={values} options={options} onChange={onChange} placeholder="请选择地址" showSearch/>
    </div>
  )
}

export default RegionSelect;
